#include "database.h"
#include "file.h"

int database::allocated_ids;
std::list<basic_item*> database::elems;

void database::insert(basic_item* val)
{
    val->set_id(alloc_id());
    elems.insert(elems.end(), val);
}

database::iterator database::find_id(const std::string& id)
{
    return std::find_if(elems.begin(), elems.end(), id_equal(id));
}

void database::remove_id(const std::string& id)
{
    elems.remove_if(id_equal(id));
}

database::iterator database::begin()
{
    return elems.begin();
}

database::iterator database::end()
{
    return elems.end();
}

void database::save()
{
    file::write_init(allocated_ids);

    std::for_each(elems.begin(), elems.end(), file::write);

    file::close();
}

void database::init()
{
    allocated_ids = file::read_init();

    basic_item* temp;
    while ((temp = file::read()))
    {
        elems.push_back(temp);
    }

    file::close();
}

int database::get_ids()
{
    return allocated_ids;
}

std::string database::alloc_id()
{
    return to_string(++allocated_ids);
}